package com.zxk.app.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.sun.jna.platform.win32.WinDef;
import com.zxk.app.ContextHolder;
import com.zxk.app.dto.TaskMappingDto;
import com.zxk.app.vo.AppStartVo;
import com.zxk.controller.StartController;
import com.zxk.service.TaskProgressService;
import com.zxk.util.HwndUtil;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.util.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author: 舟小亢
 * @date: 2023-11-17 23:17
 */
public class AppController {

    private static Logger LOG = LoggerFactory.getLogger(AppController.class);


    @FXML
    private TextArea scheduleTaskText;

    /**
     * 获取的句柄
     */
    @FXML
    private ListView<String> handleListView;

    /**
     * 选择启动的句柄
     */
    @FXML
    private ListView<String> selectedHandleListView;

    /**
     * 启动的句柄名
     */
    @FXML
    private TextField handleName;

    /**
     * 任务进展Text框
     */
    @FXML
    private TextArea taskProgressText;

    /**
     * 选择队长下拉框
     */
    @FXML
    private ComboBox<String> selectCaptainCB;


    /**
     * 默认的初始化方法
     */
    @FXML
    private void initialize() {
        // 初始化句柄监听器
        initListView();
        // 初始化任务进度定时器
        initTaskProgressTimer();
        // 初始化选择队长下拉框监听器
        initSelectCaptainCBListener();
    }

    private void initSelectCaptainCBListener() {
        // 初始化下拉框句柄
        Map<String, WinDef.HWND> hwndMap = HwndUtil.getHwndMap(handleName.getText());
        for (String hwnd : hwndMap.keySet()) {
            ContextHolder.addCaptainItems(hwnd);
        }
        // 设置默认值
        selectCaptainCB.setItems(ContextHolder.getCaptainItems());
        if (CollectionUtil.isNotEmpty(ContextHolder.getCaptainItems())) {
            String captainName = ContextHolder.getCaptainItems().get(0);
            selectCaptainCB.setValue(captainName);
            ContextHolder.setCaptainName(captainName);
            LOG.info("刷新队长名为:{}", captainName);
        }
    }

    private void initTaskProgressTimer() {
        // 设置每3秒刷新一次TextField
        Timeline timeline = new Timeline(new KeyFrame(
                Duration.seconds(3),
                a -> taskProgressText.setText(TaskProgressService.getProgress())
        ));
        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.play();
    }

    private void initListView() {
        // 设置可多选
        handleListView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        // 设置监听器
        handleListView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            ObservableList<String> selectedItems = handleListView.getSelectionModel().getSelectedItems();
            selectedHandleListView.getItems().clear();
            selectedHandleListView.getItems().addAll(selectedItems);
            // 更新启动项里的句柄
            HwndUtil.selectHwndsMap.clear();
            for (String selectedItem : selectedItems) {
                HwndUtil.selectHwndsMap.put(selectedItem, HwndUtil.hwndsMap.get(selectedItem));
            }
            LOG.info("更新选择句柄：{}", JSONUtil.toJsonStr(HwndUtil.selectHwndsMap.keySet()));
        });
        // 设置默认值
        Map<String, WinDef.HWND> hwndMap = HwndUtil.getHwndMap(handleName.getText());
        handleListView.getItems().clear();
        handleListView.getItems().addAll(hwndMap.keySet());
    }

    /**
     * 单人任务集合
     */
    private static final StringBuilder SINGLE_TASK = new StringBuilder()
            .append(TaskMappingDto.SCRATCH_TICKET).append(",")
            .append(TaskMappingDto.USE_ENERGY).append(",")
            .append(TaskMappingDto.RECEIVE_POINT).append(",")
            .append(TaskMappingDto.USE_MAP).append(",")
            .append(TaskMappingDto.SELL_SILVER_COIN).append(",")
            .append(TaskMappingDto.AQ_TASK).append(",")
            .append(TaskMappingDto.EXAM_TASK).append(",")
            .append(TaskMappingDto.MAP_TASK).append(",")
            .append(TaskMappingDto.SECRET_AREA).append(",")
            .append(TaskMappingDto.DART_CAR);

    /**
     * 单人任务集合(留活力)
     */
    private static final StringBuilder SINGLE_TASK_RETAIN_ENERGY = new StringBuilder()
            .append(TaskMappingDto.SCRATCH_TICKET).append(",")
            .append(TaskMappingDto.RECEIVE_POINT).append(",")
            .append(TaskMappingDto.USE_MAP).append(",")
            .append(TaskMappingDto.SELL_SILVER_COIN).append(",")
            .append(TaskMappingDto.AQ_TASK).append(",")
            .append(TaskMappingDto.EXAM_TASK).append(",")
            .append(TaskMappingDto.MAP_TASK).append(",")
            .append(TaskMappingDto.SECRET_AREA).append(",")
            .append(TaskMappingDto.DART_CAR);

    /**
     * 快速单人任务集合
     */
    private static final StringBuilder SINGLE_TASK_FAST = new StringBuilder()
            .append(TaskMappingDto.SCRATCH_TICKET).append(",")
            .append(TaskMappingDto.USE_ENERGY).append(",")
            .append(TaskMappingDto.RECEIVE_POINT).append(",")
            .append(TaskMappingDto.MAP_TASK).append(",")
            .append(TaskMappingDto.SECRET_AREA).append(",")
            .append(TaskMappingDto.DART_CAR);

    /**
     * 快速单人任务集合(留活力)
     */
    private static final StringBuilder SINGLE_TASK_FAST_RETAIN_ENERGY = new StringBuilder()
            .append(TaskMappingDto.SCRATCH_TICKET).append(",")
            .append(TaskMappingDto.RECEIVE_POINT).append(",")
            .append(TaskMappingDto.MAP_TASK).append(",")
            .append(TaskMappingDto.SECRET_AREA).append(",")
            .append(TaskMappingDto.DART_CAR);


    private static Map<String, StringBuilder> selectTaskMap = new LinkedHashMap() {{
        // 登录+单人+抓鬼
        put("selectTaskB1", new StringBuilder()
                .append(TaskMappingDto.LOGIN_GAME).append(",")
                .append(SINGLE_TASK).append(",")
                .append(TaskMappingDto.FIGHT_GHOST));
        // 登录+单人(留活力)+抓鬼
        put("selectTaskB2", new StringBuilder()
                .append(TaskMappingDto.LOGIN_GAME).append(",")
                .append(SINGLE_TASK_RETAIN_ENERGY).append(",")
                .append(TaskMappingDto.FIGHT_GHOST));
        // 所有副本+抓鬼
        put("selectTaskB3", new StringBuilder()
                .append(TaskMappingDto.HARD_INSTANCE_1).append(",")
                .append(TaskMappingDto.NORMAL_INSTANCE_1).append(",")
                .append(TaskMappingDto.NORMAL_INSTANCE_2).append(",")
                .append(TaskMappingDto.FIGHT_GHOST).append(","));
        // 单人+抓鬼
        put("selectTaskB4", new StringBuilder()
                .append(SINGLE_TASK).append(",")
                .append(TaskMappingDto.FIGHT_GHOST));
        // 单人(留活力)+抓鬼
        put("selectTaskB5", new StringBuilder()
                .append(SINGLE_TASK_RETAIN_ENERGY).append(",")
                .append(TaskMappingDto.FIGHT_GHOST));
        // 普通副本+抓鬼
        put("selectTaskB6", new StringBuilder()
                .append(TaskMappingDto.NORMAL_INSTANCE_1).append(",")
                .append(TaskMappingDto.NORMAL_INSTANCE_2).append(",")
                .append(TaskMappingDto.FIGHT_GHOST).append(","));
        // 登录+快速日常+抓鬼
        put("selectTaskB7", new StringBuilder()
                .append(TaskMappingDto.LOGIN_GAME).append(",")
                .append(SINGLE_TASK_FAST).append(",")
                .append(TaskMappingDto.FIGHT_GHOST));
        // 快速日常+抓鬼
        put("selectTaskB8", new StringBuilder()
                .append(SINGLE_TASK_FAST).append(",")
                .append(TaskMappingDto.FIGHT_GHOST));
        // 登录+快速日常（留活力）+抓鬼
        put("selectTaskB9", new StringBuilder()
                .append(TaskMappingDto.LOGIN_GAME).append(",")
                .append(SINGLE_TASK_FAST_RETAIN_ENERGY).append(",")
                .append(TaskMappingDto.FIGHT_GHOST));
        // 快速日常（留活力）+抓鬼
        put("selectTaskB10", new StringBuilder()
                .append(SINGLE_TASK_FAST_RETAIN_ENERGY).append(",")
                .append(TaskMappingDto.FIGHT_GHOST));
        // 3本(提前组好队)+单人日常+抓鬼
        put("selectTaskB11", new StringBuilder()
                .append(TaskMappingDto.HARD_INSTANCE_1).append(",")
                .append(TaskMappingDto.NORMAL_INSTANCE_1).append(",")
                .append(TaskMappingDto.NORMAL_INSTANCE_2).append(",")
                .append(SINGLE_TASK).append(",")
                .append(TaskMappingDto.FIGHT_GHOST));
    }};

    /**
     * 选择任务复选框
     *
     * @param event
     */
    @FXML
    private void handleCheckBoxSelection(MouseEvent event) {
        CheckBox checkBox = (CheckBox) event.getSource();
        // 选中状态就添加到map中
        if (checkBox.isSelected()) {
            AppStartVo.TASK_MAP.put(checkBox.getId(), checkBox.getText());
        } else {
            // 取消状态就从map中移除
            AppStartVo.TASK_MAP.remove(checkBox.getId(), checkBox.getText());
        }
        // 刷新text内容
        StringBuilder sb = new StringBuilder();
        for (String value : AppStartVo.TASK_MAP.values()) {
            sb.append(value);
            sb.append(",");
        }
        if (sb.length() == 0) {
            return;
        }
        scheduleTaskText.setText(sb.substring(0, sb.length() - 1));
    }

    /**
     * 启动任务按钮
     *
     * @param event
     */
    @FXML
    private void handleStartButton(MouseEvent event) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        if (AppStartVo.TASK_MAP.size() == 0) {
            alert.setTitle("提示");
            alert.setHeaderText(null);
            alert.setContentText("你还未选择任何任务！");
            alert.showAndWait();
            return;
        }
        alert.setTitle("提示");
        alert.setHeaderText(null);
        alert.setContentText("启动成功！");
        alert.showAndWait();
        Button button = (Button) event.getSource();
        button.setDisable(true);
        button.setText("运行中");
        StartController.run();
    }

    /**
     * 一键选择任务按钮
     *
     * @param event
     */
    @FXML
    private void handleSelectTaskButton(MouseEvent event) {
        Button button = (Button) event.getSource();
        StringBuilder taskInfo = selectTaskMap.get(button.getId());
        String[] split = taskInfo.toString().split(",");
        // 刷新text内容
        StringBuilder sb = new StringBuilder();
        for (String taskName : split) {
            AppStartVo.TASK_MAP.put(taskName, taskName);
            sb.append(taskName);
            sb.append(",");
        }
        if (sb.length() == 0) {
            return;
        }
        scheduleTaskText.setText(sb.substring(0, sb.length() - 1));
        // 如果选择了三本后单人任务，则副本后不退队
        if (button.getId().equals("selectTaskB11")){
            ContextHolder.getIsQuitTeamAfterInstance().set(true);
            LOG.warn("设置副本后退队");
        }
    }


    /**
     * 清空任务按钮
     *
     * @param event
     */
    @FXML
    private void handleClearButton(MouseEvent event) {
        AppStartVo.TASK_MAP.clear();
        scheduleTaskText.clear();
    }

    @FXML
    private void getHandles() {
        // 获取句柄
        Map<String, WinDef.HWND> hwndMap = HwndUtil.getHwndMap(handleName.getText());
        handleListView.getItems().clear();
        handleListView.getItems().addAll(hwndMap.keySet());

        // 刷新选择队长下拉框
        ContextHolder.updateCaptainItems(hwndMap.keySet());
        if (CollectionUtil.isNotEmpty(ContextHolder.getCaptainItems())) {
            String captainName = ContextHolder.getCaptainItems().get(0);
            selectCaptainCB.setValue(captainName);
            ContextHolder.setCaptainName(captainName);
            LOG.info("刷新队长名为:{}", captainName);
        }
    }

    @FXML
    private void onSelectCaptain(ActionEvent event) {
        String selectedItem = selectCaptainCB.getSelectionModel().getSelectedItem();
        LOG.info("你选择了队长: {}", selectedItem);
        // 刷新选择队长下拉框
        selectCaptainCB.setValue(selectedItem);
        ContextHolder.setCaptainName(selectedItem);
    }

}
